package linkedlist;

import java.util.*;

/**
 * Created by Tzachi on 18/10/2014.
 */

public class MinSwaps {

    private final static Set<String> allPermutationsSet = new HashSet<>();

    public static int easeStrings(String a, String b) {
        if (a.equals(b)) return 0;
        allPermutationsSet.add(a);
        return minswaps(b, 1, calcAllPossibleMoves(a));
    }

    public static int minswaps(String target, int moves, Set<String> permutations) {
        if (permutations.contains(target)) {
            return moves;
        }
        Set<String> newPermutations = new HashSet<>();
        for (String permutation : permutations) {
            newPermutations.addAll(calcAllPossibleMoves(permutation));
        }
        return 1 + minswaps(target, moves, newPermutations);
    }

    public static Set<String> calcAllPossibleMoves(String str) {
        Set<String> results = new HashSet<>();
        for (int i = 0; i < str.length(); i++) {
            char[] chars = str.toCharArray();
            char swapWith = chars[(i + 1) % chars.length];
            chars[(i + 1) % chars.length] = chars[i];
            chars[i] = swapWith;
            String permutation = new String(chars);
            // if we have seen it before it means we reached it with less move than current moves;
            if (!allPermutationsSet.contains(permutation)) {
                results.add(permutation);
                allPermutationsSet.add(permutation);
            }
        }
        return results;
    }
    public static void main(String[] args) {
        String a = "aabaa";
        String b = "baaaa";
        System.out.println(easeStrings(a, b));
    }

}
